package com.wx.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropertyUtils {
	/**
	 * properites文件名为key一个Map
	 */
	private static Map<String, Properties> proMap = new HashMap<String, Properties>();
	
	public static synchronized Properties getProperties(String filePath) {
		try {
			if(proMap.containsKey(filePath)) {
	        	return proMap.get(filePath);
            } else {
    			Properties prop = new Properties();
                prop.load(PropertyUtils.class.getResourceAsStream(filePath));
            	proMap.put(filePath, prop);
            	return prop;
             }
		} catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @param key propertiesd对应的key
	 * @param filePath 文件相对路径 如：com/properties/server.properties
	 * @return key对应的value
	 */
	public static String getProperty(String key , String filePath) {
		Properties property = PropertyUtils.getProperties(filePath);
		return (String)property.get(key);
	}
	
	/**
	 * 根据key获取键值
	 * @return
	 */
	public static String getValue(String key, String filepath) {
		InputStream in = PropertyUtils.class.getClassLoader()
				.getResourceAsStream(filepath);
		Properties p = new Properties();
		try {
			p.load(in);
			in.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return p.getProperty(key);
	}
	
	/**
	 * 根据文件路径获取属性对象
	 * @param filepath
	 * @return
	 */
	public static Properties getPropertyFile(String filepath){
		InputStream in = PropertyUtils.class.getClassLoader()
				.getResourceAsStream(filepath);
		Properties p = new Properties();
		try {
			p.load(in);
			in.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return p;
	}
	
	public static Object getProperty(String key){
		Properties p = PropertyUtils.getPropertyFile("properties/config.properties");
		return p.get(key);
	}
}
